<?php

namespace Admin\Controllers;
use Forms\ChangepassForm;
use Models\Users;


class AdminController extends ControllerBase {

    public function logoutAction() {
        $this->auth->remove();
        $this->response->redirect('admin/login');
    }

    public function securityAction() {
        $form = new ChangepassForm();
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if ($user) {
            $password = $user->password;
            $user->password = '';
            $form = new ChangepassForm($user);
            if ($this->request->isPost()) {
                $request = $this->request->getPost();
                //$request['username'] = $user->username;
                //$request['email'] = $user->email;
                if ($form->isValid($request)) {
                    if ($this->request->getPost('password')) {
                        $user->password = $this->security->hash($this->request->getPost('password'));
                    } else {
                        $user->password = $password;
                    }
                    $user->updatetime = date('Y-m-d H:i:s');
                    if ($user->save()) {
                        $form->appendMessage("Thay đổi mật khẩu thành công", "changepass_info", null);
                    } else {
                        $form->appendMessage("Cập nhật lỗi", "changepass_info", null);
                    }
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "changepass_info", null);
                    }
                }
            }
            $this->view->form = $form;
            $this->view->users = $user;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'admin',
                'controller' => 'error',
                'action' => 'notAvailable'
            ));
        }
    }

    public function configAction() {
        
    }

}
